import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.Scanner;
import java.util.Vector;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

//@author A0099655J
public class Database {

	public String filename;
	File _file;
	

	//@author A0099655J
	// Constructor
	public Database(String filename) {
		this.filename = filename;
		this._file = checkIfFileExists(this.filename);
		
		assert _file.exists();
	}

	//@author A0099655J
	public File checkIfFileExists(String filename) {
		File f = new File(this.filename);
		if (!f.exists()) {
			try {
				f.createNewFile();
				System.out.println(filename + " created successfully.");
			} catch (IOException e) {
				// returns error while creating file
				e.printStackTrace();
			}
		}
		
		return f;
	}

	//@author A0099655J
	// When Task handler is implemented, change return type from 'void' to 'Vector<Task>'
	public Vector<Task> read() {
		
		Workbook w1;
		Vector<Task> contents = new Vector<Task>();
		DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
		
		try {
			w1 = Workbook.getWorkbook(this._file);
			
			Sheet sheet = w1.getSheet(0);
			
			int rows = sheet.getRows();
			//System.out.println("i:"+rows);
			
			for (int i=1; i<rows; i++) {
				boolean completed = Boolean.parseBoolean(sheet.getCell(0,i).getContents());
				String startTime = sheet.getCell(1,i).getContents().trim();
				String endTime = sheet.getCell(2,i).getContents().trim();
				String desc = sheet.getCell(3,i).getContents();

				DateTime startDT = formatter.parseDateTime(startTime);
				DateTime endDT = formatter.parseDateTime(endTime);
				
				// for when appropriate Task handler is included
				Task temp = new Task(desc, startDT, endDT, completed);
				contents.add(temp);
				
				assert !contents.isEmpty();
				
			}
		} catch (BiffException | IOException e) {
			e.printStackTrace();
		}
		return contents;
	}
	


	//@author A0099655J
	public void write(Vector<Task> contents) {
		Scanner sc2 = new Scanner(System.in);
		
		// Initialise workbook
		WorkbookSettings ws = new WorkbookSettings();
	    ws.setLocale(new Locale("en", "EN"));
	    WritableWorkbook workbook;
		try {
			workbook = Workbook.createWorkbook(new File(filename), ws);
		
		   
		    // Initialise first sheet in workbook
			WritableSheet sheet = workbook.createSheet("Storage", 0);
					
			// set Text format
			WritableCellFormat wrappedText = new WritableCellFormat(WritableWorkbook.ARIAL_10_PT);
			wrappedText.setWrap(true);
		    
			Label l = new Label(0,0, "Completed?", wrappedText);
			sheet.addCell(l);
			l = new Label(1,0, "Start time", wrappedText);
			sheet.addCell(l);
			l = new Label(2,0, "End time/Deadline", wrappedText);
			sheet.addCell(l);
			l = new Label(3,0, "Description", wrappedText);
			sheet.addCell(l);
			
			DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
			
			for (int i=0; i < contents.size(); i++) {
				Task current = contents.get(i);
				String desc = current.getDescription();
				DateTime taskStartDT = current.getStartDateTime(),
						 taskEndDT = current.getEndDateTime();
				String startTime = taskStartDT.toString(formatter);
				String endTime = taskEndDT.toString(formatter);
				
				boolean completed = current.getStatus();
				sheet = writeToSheet(sheet, wrappedText, i+1, completed, startTime, endTime, desc);
			}
			
			workbook.write();
			workbook.close();
	
		} catch (IOException e) {
			e.printStackTrace();
		} catch (WriteException e) {
			e.printStackTrace();
		}
		sc2.close();
	}

	//@author A0099655J
	public static WritableSheet writeToSheet(WritableSheet sheet,
			WritableCellFormat format, int i, boolean completed,
			String startTime, String endTime, String desc) throws WriteException,
			RowsExceededException {
		
		// Write to xls sheet
		Label l;
		l = new Label(0,i, String.valueOf(completed), format);
		sheet.addCell(l);
		l = new Label(1,i, startTime, format);
		sheet.addCell(l);
		l = new Label(2,i, endTime, format);
		sheet.addCell(l);
		l = new Label(3,i, desc, format);
		sheet.addCell(l);
			
		return sheet;
	}

}
